from flask import jsonify
from flask import current_app
from flask import render_template
from flask import request

from info import constants, db
from info.module.admin import admin_blu
from info.models import Product
from info.tools.image_storage import storage
from info.tools.response_code import RET


@admin_blu.route('/news_edit_detail', methods=["get", "post"])
def product_edit_detail():

    if request.method == "GET":

        return render_template('admin/news_edit_detail.html')

    # 取到Post进来的数据
    title = request.form.get("title")
    content = request.form.get("content")
    index_image = request.files.get("index_image")

    # 1.1 判断数据是否有值
    if not all([title, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 1.2 尝试读取图片
    if index_image:
        try:
            index_image = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        # 2. 将标题图片上传到七牛
        try:
            key = storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    product = Product()
    # 3. 设置相关数据
    product.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    product.name = title
    product.content = content

    try:
        db.session.add(product)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="提交错误")

    return jsonify(errno=RET.OK, errmsg="OK")

